import { FC } from "react";
import { Navigate, RouteProps } from "react-router";
import { useRecoilState } from "recoil";

import { userState } from "../stores/user";

/**
 * 刷新时,获取缓存用户信息如果不存在就跳到登录页面,存在就设置用户信息
 * @returns 渲染组件
 */
const PrivateRoute: FC<RouteProps> = ({ children }) => {
  const [user] = useRecoilState(userState);

  if (!user || !user.token) {
    const data = sessionStorage.getItem("__BEEFSOLVE_BACKWEB__");
    if (!data) {
      return <Navigate to="/login" />;
    }
  }

  return <>{children}</>;
};

export default PrivateRoute;
